package array;

import java.util.Arrays;

public class leetCode556_nextGreaterElement {
    public int nextGreaterElement(int n) {
        String s = String.valueOf(n);
        char[] chars = s.toCharArray();
        int len = chars.length;
        for (int i = len - 1; i > 0; i--) {
            if(chars[i] > chars[i - 1]){
                for (int j = len - 1; j > i - 1 ; j--) {
                    if(chars[j] > chars[i - 1]){
                        swap(chars,i - 1,j);
                        Arrays.sort(chars,i,len);
                        String res = new String(chars);

                        Long ans = Long.parseLong(res);
                        if(ans > Integer.MAX_VALUE){
                            return -1;
                        }
                        return ans.intValue();
                    }
                }
            }
        }

        return -1;

    }

    public void swap(char[] nums,int i, int j){
        char tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}
